package com.ruoyi.basicsystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.basicsystem.domain.ZnAgreementCustomer;
import com.ruoyi.basicsystem.mapper.ZnSupplierMapper;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;

import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.basicsystem.domain.ZnAgreementDetail;
import com.ruoyi.basicsystem.mapper.ZnAgreementMapper;
import com.ruoyi.basicsystem.domain.ZnAgreement;
import com.ruoyi.basicsystem.service.IZnAgreementService;

import javax.crypto.SealedObject;

/**
 * 客户协议价管理Service业务层处理
 * 
 * @author nexiaozi
 * @date 2022-03-25
 */
@Service
public class ZnAgreementServiceImpl implements IZnAgreementService 
{
    @Autowired
    private ZnAgreementMapper znAgreementMapper;
    @Autowired
    private ZnSupplierMapper znSupplierMapper ;
    /**
     * 查询客户协议价管理
     * 
     * @param id 客户协议价管理主键
     * @return 客户协议价管理
     */
    @Override
    public ZnAgreement selectZnAgreementById(Long id)
    {
        return znAgreementMapper.selectZnAgreementById(id);
    }

    /**
     * 查询客户协议价管理列表
     * 
     * @param znAgreement 客户协议价管理
     * @return 客户协议价管理
     */
    @Override
    public List<ZnAgreement> selectZnAgreementList(ZnAgreement znAgreement)
    {
        znAgreement.setTenantId(SecurityUtils.getTenantId());
        znAgreement.setDeleteFlag("0");
        return znAgreementMapper.selectZnAgreementList(znAgreement);
    }
     /**
      * 查询客户协议价管理记录数
      *
      * @param znAgreement 客户协议价管理
      * @return 客户协议价管理记录数
     */
    public Integer selectZnAgreementCount(ZnAgreement znAgreement){
        znAgreement.setTenantId(SecurityUtils.getTenantId());
        return znAgreementMapper.selectZnAgreementCount(znAgreement);
    }


    /**
     * 新增客户协议价管理
     * 
     * @param znAgreement 客户协议价管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertZnAgreement(ZnAgreement znAgreement)
    {
        znAgreement.setCreateTime(DateUtils.getNowDate());
        znAgreement.setTenantId(SecurityUtils.getTenantId());
        znAgreement.setDeleteFlag("0");
        znAgreement.setStatus("0");
        znAgreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
        znAgreement.setCreateBy(SecurityUtils.getUsername());
        znAgreement.setCreateTime(new Date());
        znAgreement.setUserId(SecurityUtils.getUserId());
        znAgreement.setDeptId(SecurityUtils.getDeptId());
        znAgreement.setParentId(0l);
        int rows = znAgreementMapper.insertZnAgreement(znAgreement);
        insertZnAgreementDetail(znAgreement);
        return rows;
    }

    /**
     * 修改客户协议价管理
     * 
     * @param znAgreement 客户协议价管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateZnAgreement(ZnAgreement znAgreement)
    {
        znAgreement.setUpdateTime(DateUtils.getNowDate());
        znAgreement.setUpdateName(SecurityUtils.getLoginUser().getUser().getNickName());
        znAgreement.setUpdateBy(SecurityUtils.getUsername());
        znAgreementMapper.deleteZnAgreementDetailByAgreementId(znAgreement.getId());
        insertZnAgreementDetail(znAgreement);
        return znAgreementMapper.updateZnAgreement(znAgreement);
    }

    /**
     * 批量删除客户协议价管理
     * 
     * @param ids 需要删除的客户协议价管理主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZnAgreementByIds(Long[] ids)
    {
        znAgreementMapper.deleteZnAgreementDetailByAgreementIds(ids);
        znAgreementMapper.deleteZnAgreementByPIds(ids,SecurityUtils.getTenantId());
        return znAgreementMapper.deleteZnAgreementByIds(ids);
    }

    /**
     * 删除客户协议价管理信息
     * 
     * @param id 客户协议价管理主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZnAgreementById(Long id)
    {
        znAgreementMapper.deleteZnAgreementDetailByAgreementId(id);
        return znAgreementMapper.deleteZnAgreementById(id);
    }

    @Override
    public int updateZnAgreementStatusByIds(String status, Long[] ids) {
        return znAgreementMapper.updateZnAgreementStatusByIds(status,ids);
    }

    /**
     * 刷新用户协议价
     * 即将生效的转为生效，即将失效转为过期
     * @author nexiaozi
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshEffect() {
        //1、将失效的协议状态，转为过期，并将用户的是否使用协议价去除。
        ZnAgreement query = new ZnAgreement();
        query.setStatus("2");
        Map<String,Object> params = new HashMap<>();
        params.put("invalidTime",new Date());
        params.put("parentId",0);//不等于
        query.setParams(params);
        List<ZnAgreement> list = znAgreementMapper.selectZnAgreementList(query);
        List<Long> customerIds = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        if(list.size()>0){
            for (ZnAgreement agreement:list) {
                customerIds.add(agreement.getCustomerId());
                ids.add(agreement.getId());
            }
            if(!customerIds.isEmpty()){
                znAgreementMapper.updateZnAgreementStatusByIds("-1",ids.toArray(new Long[ids.size()]));
                int updatecount0 = znSupplierMapper.updateZnSupplierIsAgreeByIds("0",null,customerIds.toArray(new Long[customerIds.size()]));
            }
        }
        //2、将即将生效的协议状态，转为生效，并将用户的标记使用协议价。
        query = new ZnAgreement();
        query.setStatus("1");
        params = new HashMap<>();
        params.put("effectTime",new Date());
        params.put("parentId",0);//不等于
        params.put("order"," order by customer_id,effect_time");
        query.setParams(params);
        list = znAgreementMapper.selectZnAgreementList(query);
        customerIds = new ArrayList<>();
        Map<String,Long> customerIdAndAgreementIdMap =  new HashMap<>();//保存有效的生效协议
        Map<String,Long> hashCustomerIdMap =  new HashMap<>();//保存重复协议生效时间比较早的，直接设置为过期。

        if(list.size()>0){
            for (ZnAgreement agreement:list) {
                if(customerIdAndAgreementIdMap.containsKey(agreement.getCustomerId().toString())){
                    hashCustomerIdMap.put(agreement.getCustomerId().toString(),customerIdAndAgreementIdMap.get(agreement.getCustomerId().toString()));
                }
                customerIdAndAgreementIdMap.put(agreement.getCustomerId().toString(),agreement.getId());
            }
            //重复的设置为过期
            for (Map.Entry<String,Long> entry:hashCustomerIdMap.entrySet()) {
//                ids.add(entry.getValue());
                ZnAgreement znAgreement= new ZnAgreement();
//                znAgreement.setCustomerId(Long.valueOf(entry.getKey()));
                znAgreement.setStatus("-1");
                params = new HashMap<>();
                params.put("id",entry.getValue());
                params.put("parentId",0);//不等于
                znAgreement.setParams(params);
                znAgreementMapper.updateZnAgreementStatus(znAgreement);
            }
//            if(ids.size()>0){
//                znAgreementMapper.deleteZnAgreementByIds(ids.toArray(new Long[ids.size()]));
//            }
            ids = new ArrayList<>();
            for (Map.Entry<String,Long> entry:customerIdAndAgreementIdMap.entrySet()) {
                customerIds.add(Long.valueOf(entry.getKey()));
                ids.add(entry.getValue());
                ZnAgreement znAgreement= new ZnAgreement();
//                znAgreement.setCustomerId(Long.valueOf(entry.getKey()));
                znAgreement.setStatus("2");
                params = new HashMap<>();
                params.put("id",entry.getValue());
                params.put("parentId",0);//不等于
                znAgreement.setParams(params);
                znAgreementMapper.updateZnAgreementStatus(znAgreement);
            }
//            if(!customerIdAndAgreementIdMap.isEmpty()){
//                znAgreementMapper.updateZnAgreementStatusByIds("2",ids.toArray(new Long[ids.size()]));
//            }
            if(!customerIds.isEmpty()){
                int updatecount0 = znSupplierMapper.updateZnSupplierIsAgreeByIds("1",null,customerIds.toArray(new Long[customerIds.size()]));
            }
            // 3、覆盖新生效客户的原协议过期。
            for (Map.Entry<String,Long> entry:customerIdAndAgreementIdMap.entrySet()) {
                customerIds.add(Long.valueOf(entry.getKey()));
                ids.add(entry.getValue());
                ZnAgreement znAgreement= new ZnAgreement();
//                znAgreement.setCustomerId(Long.valueOf(entry.getKey()));
                znAgreement.setStatus("-1");
                params = new HashMap<>();
                params.put("customerId",Long.valueOf(entry.getKey()));
                params.put("notId",entry.getValue());
                params.put("status","2");
                params.put("parentId",0);//不等于
                znAgreement.setParams(params);
                znAgreementMapper.updateZnAgreementStatus(znAgreement);
            }
        }
    }

    /**
     * 修改客户关联协议价模板id
     * @param znAgreement
     * @return
     */
    @Override
    public int updateCustomerAgreement(ZnAgreement znAgreement) {
        return znAgreementMapper.updateCustomerAgreement(znAgreement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doCustomer(Long agreementId, Long[] customerIds) {
        int insertCount = 0;
        ZnAgreement znAgreementParam = new ZnAgreement();
        znAgreementParam.setParentId(agreementId);
        znAgreementParam.setTenantId(SecurityUtils.getTenantId());
        //查询原有的客户
        List<ZnAgreement> agreementList = znAgreementMapper.selectZnAgreementList(znAgreementParam);
        List<Long> ids = new ArrayList<>();
        for (ZnAgreement temp:agreementList) {
            ids.add(temp.getCustomerId());
        }
        if(customerIds !=null){
            if(!ids.isEmpty()){
                int updatecount0 = znSupplierMapper.updateZnSupplierIsAgreeByIds("0",SecurityUtils.getTenantId(),ids.toArray(new Long[ids.size()]));
            }
            int delCount = znAgreementMapper.deleteZnAgreementByPId(agreementId, SecurityUtils.getTenantId());
            int updatecount1 = znSupplierMapper.updateZnSupplierIsAgreeByIds("1",SecurityUtils.getTenantId(),customerIds);
            List<ZnAgreement> list = new ArrayList<>();
            for (Long customerId:customerIds) {
                ZnAgreement znAgreement = new ZnAgreement();
                znAgreement.setParentId(agreementId);
                znAgreement.setCustomerId(customerId);
                znAgreement.setCreateBy(SecurityUtils.getUsername());
                znAgreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
                znAgreement.setTenantId(SecurityUtils.getTenantId());
                znAgreement.setStatus("1");
                list.add(znAgreement);
            }
             insertCount =  znAgreementMapper.batchInsertZnAgreement(list);
            return insertCount ;
        }else{
            if(!ids.isEmpty()){
                int updatecount0 = znSupplierMapper.updateZnSupplierIsAgreeByIds("0",SecurityUtils.getTenantId(),ids.toArray(new Long[ids.size()]));
            }
            int delCount = znAgreementMapper.deleteZnAgreementByPId(agreementId, SecurityUtils.getTenantId());
            return delCount;
        }
    }

    /**
     * 目前暂未使用，
     * @param znAgreement
     * @return
     */
    @Override
    public List<ZnAgreement> selectZnAgreementTreeList(ZnAgreement znAgreement) {
        znAgreement.setTenantId(SecurityUtils.getTenantId());
        znAgreement.setDeleteFlag("0");

        List<ZnAgreement> list =  znAgreementMapper.selectZnAgreementList(znAgreement);
        List<ZnAgreement> tempList =  new ArrayList<>();
        List<ZnAgreement> resultList =  new ArrayList<>();
        List<Long> parentIds = new ArrayList<>();
        for (ZnAgreement agreement :list) {
            if(agreement.getParentId() ==0){
                List<ZnAgreement> children = getChildPerms(list,agreement.getId());
                agreement.setChildren(children);
                resultList.add(agreement);
            }
//            resultList.addAll(getChildPerms(list,agreement.getId()));
        }
//        for (Long parentId: parentIds) {
//            resultList.addAll(getChildPerms(tempList,parentId));
//        }
        System.out.println(JSON.toJSONString(resultList));
        return list;
    }

    @Override
    public List<ZnAgreementDetail> selectZnAgreementDetailList(ZnAgreement znAgreement) {
        znAgreement.setTenantId(SecurityUtils.getTenantId());
        return znAgreementMapper.selectZnAgreementDetailList(znAgreement);
    }

    @Override
    public List<Map<String, Object>> selectCustomerHaveAgreement(ZnAgreement znAgreement) {
        return znAgreementMapper.selectCustomerHaveAgreement(znAgreement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doCustomer(ZnAgreementCustomer znAgreementCustomer) {
        List<ZnAgreement> list = new ArrayList<>();
        znSupplierMapper.updateZnSupplierIsAgreeByPid("0",znAgreementCustomer.getAgreementId(),SecurityUtils.getTenantId());
        znAgreementMapper.deleteZnAgreementByPId(znAgreementCustomer.getAgreementId(),SecurityUtils.getTenantId());
        for (ZnAgreement agreement:znAgreementCustomer.getCustomerList()) {
            agreement.setParentId(znAgreementCustomer.getAgreementId());
            agreement.setCreateBy(SecurityUtils.getUsername());
            agreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
            agreement.setTenantId(SecurityUtils.getTenantId());
            agreement.setStatus("1");
            agreement.setDeleteFlag("0");
            list.add(agreement);
        }
        int insertCount =  znAgreementMapper.batchInsertZnAgreement(list);
        int updateCount = znSupplierMapper.updateZnSupplierIsAgreeByPid("1",znAgreementCustomer.getAgreementId(),SecurityUtils.getTenantId());
        if(insertCount ==0 || updateCount ==0){
            throw new ServiceException("设置客户协议价异常");
        }
        return insertCount;
    }

    /**
     * 新增协议商品详情信息
     * 
     * @param znAgreement 客户协议价管理对象
     */@Transactional(rollbackFor = Exception.class)
    public void insertZnAgreementDetail(ZnAgreement znAgreement)
    {
        List<ZnAgreementDetail> znAgreementDetailList = znAgreement.getZnAgreementDetailList();
        Long id = znAgreement.getId();
        if (StringUtils.isNotNull(znAgreementDetailList))
        {
            List<ZnAgreementDetail> list = new ArrayList<ZnAgreementDetail>();
            for (ZnAgreementDetail znAgreementDetail : znAgreementDetailList)
            {
                znAgreementDetail.setAgreementId(id);
                znAgreementDetail.setCustomerId(znAgreement.getCustomerId());
                znAgreementDetail.setTenantId(znAgreement.getTenantId());
                znAgreementDetail.setDeleteFlag("0");
                list.add(znAgreementDetail);
            }
            if (list.size() > 0)
            {
                znAgreementMapper.batchZnAgreementDetail(list);
            }
        }
    }
    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<ZnAgreement> getChildPerms(List<ZnAgreement> list, Long parentId)
    {
        List<ZnAgreement> returnList = new ArrayList<ZnAgreement>();
        for (Iterator<ZnAgreement> iterator = list.iterator(); iterator.hasNext();)
        {
            ZnAgreement t = (ZnAgreement) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
//                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<ZnAgreement> list, ZnAgreement t)
    {
        // 得到子节点列表
        List<ZnAgreement> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ZnAgreement tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ZnAgreement> getChildList(List<ZnAgreement> list, ZnAgreement t)
    {
        List<ZnAgreement> tlist = new ArrayList<ZnAgreement>();
        Iterator<ZnAgreement> it = list.iterator();
        while (it.hasNext())
        {
            ZnAgreement n = (ZnAgreement) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ZnAgreement> list, ZnAgreement t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
